package com.dkd.findmyfriends;

import java.io.InputStream;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Movie;
import android.util.AttributeSet;
import android.view.View;

public class GifView extends View {

	private Movie movie;
	private int gifId = -1;
	private long movieStart;

	public GifView(Context context, AttributeSet attrs) {
	    super(context, attrs);
	    if(!isInEditMode()) {
		    setGifId(R.drawable.loading);
	    	initializeView();
	    }
	}
	
	private void setGifId(int id) {
		gifId = id;
	    initializeView();
	}
	
	private void initializeView() {
		if(gifId != -1) {
		    InputStream is = getContext().getResources().openRawResource(gifId);
		    movie = Movie.decodeStream(is);
		}
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
	    canvas.drawColor(Color.TRANSPARENT);
	    super.onDraw(canvas);
	    long now = android.os.SystemClock.uptimeMillis();
	    if (movieStart == 0) {
	        movieStart = now;
	    }
	    if (movie != null) {
	        int relTime = (int) ((now - movieStart) % movie.duration());
	        movie.setTime(relTime);
	        movie.draw(canvas, getWidth()/2 - movie.width()/2, 20);
	        this.invalidate();
	    }
	}

}
